package com.chainyoung.common.base;


import android.app.Activity;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.IBinder;
import android.support.v7.app.AlertDialog;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chainyoung.common.R;
import com.chainyoung.common.common_widget.CustomToolbar;
import com.chainyoung.common.constant.LibConstant;
import com.chainyoung.common.di.AppComponent;
import com.chainyoung.common.event.BaseEvent;
import com.chainyoung.common.mvp.BasePresenter;
import com.chainyoung.common.utils.ClipboardUtil;
import com.chainyoung.common.utils.CommonUtil;
import com.chainyoung.common.utils.ToastUtil;
import com.chainyoung.router.RouterConstants;
import com.chainyoung.router.RouterUtils;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import javax.inject.Inject;

import static com.chainyoung.common.constant.CommonStringConstants.DAPP_URL_PREFIX;
import static com.chainyoung.common.constant.CommonStringConstants.URL;

public abstract class BaseActivity<P extends BasePresenter> extends SimpleActivity {

    protected RelativeLayout toolbar;
    //protected CustomToolbar toolbar;

    public ImageView mBarLeftImageView;
    public TextView mCurrentTtile;
    public ImageView mBarRightImageView;
    public ImageView mBarRightLeftImageView;
    public TextView mBarRightTextView;
    public TextView mBarLeftTextView;

    @Inject
    protected P mPresenter;


    @Override
    protected void onViewCreated() {
        EventBus.getDefault().register(this);
        toolbar = findViewById(R.id.toolbar);
        ClipboardUtil.init(mContext);
        if (toolbar != null) {
            initToolbar();
        }
        setupActivityComponent(mAppComponent);//依赖注入

    }

    private void initToolbar() {
        //setSupportActionBar(toolbar);
        mBarLeftImageView = (toolbar.findViewById(R.id.iv_left_image));
        mCurrentTtile = (toolbar.findViewById(R.id.title));
        mBarRightImageView = (toolbar.findViewById(R.id.iv_toolbar_right));
        mBarRightTextView = (toolbar.findViewById(R.id.tv_toolbar_right));
        mBarRightLeftImageView = (toolbar.findViewById(R.id.iv_toolbar_right_left));
        mBarLeftTextView = (toolbar.findViewById(R.id.tv_toolbar_left));

        if (mBarRightLeftImageView != null) {
            mBarLeftImageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onLeftViewClicked(v);
                }
            });
        }

        if (mBarRightImageView != null) {
            mBarRightImageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onRightImgClicked(v);
                }
            });
        }

        if (mBarRightLeftImageView != null) {
            mBarRightLeftImageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onRightLeftImgClicked(v);
                }
            });
        }

        if (mBarRightTextView != null) {
            mBarRightTextView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onRightTxtClicked(v);
                }
            });
        }

        if (mBarLeftTextView != null) {
            mBarLeftTextView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onLeftTxtClicked(v);
                }
            });
        }


    }





    public void onRightTxtClicked(View v) {

    }

    public void onLeftTxtClicked(View v) {

    }

    public void onRightLeftImgClicked(View v) {

    }

    public void onRightImgClicked(View v) {
    }


    /**
     * 标题栏左边被点击的方法
     * 默认为关闭当前界面
     */
    public void onLeftViewClicked(View view) {
        finish();
    }


    /**
     * 设置bar最右边图标
     *
     * @param rsID
     */
    public void showAndSetBarRightIcon(int rsID) {
        if (mBarRightImageView != null) {
            mBarRightImageView.setImageResource(rsID);
            mBarRightImageView.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 设置bar最右边图标
     *
     * @param rs
     */
    public void showAndSetBarRightIcon(Drawable rs) {
        if (mBarRightImageView != null) {
            mBarRightImageView.setImageDrawable(rs);
            mBarRightImageView.setVisibility(View.VISIBLE);
        }
    }


    /**
     * 设置bar右边第二个图标
     *
     * @param rsID
     */
    public void showAndSetBarRightLeftIcon(int rsID) {
        if (mBarRightLeftImageView != null) {
            mBarRightLeftImageView.setImageResource(rsID);
            mBarRightLeftImageView.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 设置bar最右边text
     *
     * @param rsID
     */
    public void showAndSetBarRightText(int rsID) {
        showAndSetBarRightText(getString(rsID));
    }

    /**
     * 设置bar最右边text
     *
     * @param
     */
    public void showAndSetBarRightText(String rightStr) {
        if (mBarRightTextView != null) {
            mBarRightTextView.setText(rightStr);
            mBarRightTextView.setVisibility(View.VISIBLE);
        }
    }

    public void setCurrentTitle(int rsId) {
        if (mCurrentTtile != null) {
            mCurrentTtile.setText(getString(rsId));
        }

    }

    public void setCurrentTitle(String title) {
        if (mCurrentTtile != null) {
            mCurrentTtile.setText(title);
        }
    }


    /**
     * 提供AppComponent(提供所有的单例对象)给子类，进行Component依赖
     */
    protected abstract void setupActivityComponent(AppComponent appComponent);

//    @Override
//    public Resources getResources() {
//        Resources res = super.getResources();
//        Configuration config=new Configuration();
//        config.setToDefaults();
//        res.updateConfiguration(config,res.getDisplayMetrics() );
//        return res;
//    }
//
//    @Override
//    public void onConfigurationChanged(Configuration newConfig) {
//        if (newConfig.fontScale != 1)//非默认值
//            getResources();
//        super.onConfigurationChanged(newConfig);
//
//    }

    //****************************************登陆处理*******************************************************//

    @Subscriber
    public void onUserLoginIn(BaseEvent event) {
        if (event.getCode() == BaseEvent.EventCode.LOGIN_IN) {
            onLoginIn(event);
        }

    }

    public void onLoginIn(BaseEvent event) {
        CommonUtil.loginInSuccess(event);
    }

    @Subscriber
    public void onLoginOut(BaseEvent evnet) {
        if (evnet.getCode() == BaseEvent.EventCode.LOGIN_OUT) {
            CommonUtil.signOutSuccess();
        }
    }

    @Subscriber
    public void onOtherLogin(BaseEvent evnet) {
        if (evnet.getCode() == BaseEvent.EventCode.OTHER_DEVICE_LOGIN) {
            CommonUtil.signOutSuccess();
            AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
            builder.setMessage("登陆缓存失效" + "\n" + "点击确定重新登陆")
                    .setCancelable(false)
                    .setNegativeButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent mIntent = new Intent("com.chainyoung.trademarket.ui.LoginActivity");
                            startActivity(mIntent);
                        }
                    });
            builder.create();
            builder.show();
        }
    }

    @Override
    public void showReloginDialog(int stringId) {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setMessage(mContext.getString(stringId))
                .setCancelable(false)
                .setPositiveButton(mContext.getString(R.string.confirm), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        CommonUtil.signOutSuccess();
                        Intent mIntent = new Intent("com.chainyoung.trademarket.ui.LoginActivity");
                        startActivity(mIntent);
                        finish();
                    }
                });
        builder.create();
        builder.show();
    }


    //----------------------------------------------------生命周期---------------------------------------------------------

    @Override
    protected void onResume() {
        super.onResume();
        //跳转dapp 浏览器打开指定dapp
        gotoDapp();

    }

    private void gotoDapp() {
        final String url = ClipboardUtil.getInstance().getClipText(mContext,0);
        boolean isMainActivityExsit = false;
        for (Activity activity : mAppComponent.appManager().getActivityList()) {
            if (activity.getClass().getSimpleName().equals("MainMarketActivity")) {
                isMainActivityExsit = true;
            }
        }
        if (!isMainActivityExsit) {
            return;
        }
        if (url != null && url.startsWith(DAPP_URL_PREFIX)) {
            AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
            builder.setTitle(R.string.common_remind)
                    .setMessage(R.string.find_dapp_url)
                    .setCancelable(false)
                    .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ClipboardUtil.getInstance().clearClip();
                            dialog.dismiss();
                        }
                    })
                    .setPositiveButton(R.string.common_open, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ClipboardUtil.getInstance().clearClip();
                            RouterUtils.getInstance()
                                    .build(RouterConstants.PATH_OTHERAPP)
                                    .withString("title", url.substring(DAPP_URL_PREFIX.length()))
                                    .withString(URL, url.substring(DAPP_URL_PREFIX.length()))
                                    .navigation(mContext);
                            dialog.dismiss();
                        }
                    });
            builder.create();
            builder.show();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.onDestroy();
        }
        this.mPresenter = null;
        EventBus.getDefault().unregister(this);

    }


    //****************************************点击空白处键盘消失处理*******************************************************//]




    /**
     * 点击空白处关闭软键盘逻辑
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideKeyboard(v, ev)) {
                hideKeyboard(v.getWindowToken());
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    private boolean NeedHandleEditSelf = false;

    public void setNeedHandleEditSelf(boolean needHandleEditSelf) {
        NeedHandleEditSelf = needHandleEditSelf;
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时则不能隐藏
     *
     * @param v
     * @param event
     * @return
     */
    private boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0],
                    top = l[1],
                    bottom = top + v.getHeight(),
                    right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击EditText的事件，忽略它。
                return false;
            } else {
                if (NeedHandleEditSelf) {
                    return false;
                }
                return true;
            }
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditText上，和用户用轨迹球选择其他的焦点
        return false;
    }

    /**
     * 获取InputMethodManager，隐藏软键盘
     *
     * @param token
     */
    private void hideKeyboard(IBinder token) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }


}
